//
//  SEGUtils.m
//  SEGBasic
//
//  Created by 刘山 on 2018/3/15.
//  Copyright © 2018年 刘山. All rights reserved.
//
#import "SEGUtils.h"
#import <sys/utsname.h>
#include <CommonCrypto/CommonCrypto.h>
#import <AVFoundation/AVFoundation.h>
#import <AVFoundation/AVFoundation.h>

#if __has_include(<Commom/SEGLayoutMacro.h>)
#import <Commom/SEGLayoutMacro.h>
#else
#import "SEGLayoutMacro.h"
#endif

#define LAST_RUN_VERSION_KEY @"last_run_version_of_application" //本地存储的版本号

@implementation SEGUtils
/**
 *  应用程序的发布版本号
 * @author Sam
 */
+(NSString*)segBundleShortVersionString{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
}

/**
 * 设备的型号，例如iPhone5、iPhone6、iphone7等
 * @author Sam
 * @return iPhone5、iPhone6、iphone7等
 */
+ (NSString*)segDeviceHardWareName{
    __block NSString *status = @"其他";
    
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* code = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    NSDictionary* deviceNamesByCode = @{
                                        @"i386"      : @"Simulator",
                                        @"x86_64"    : @"Simulator",
                                        @"iPod1,1"   : @"iPod1",
                                        @"iPod2,1"   : @"iPod2",
                                        @"iPod3,1"   : @"iPod3",
                                        @"iPod4,1"   : @"iPod4",
                                        @"iPod5,1"   : @"iPod5",
                                        @"iPad2,1"   : @"iPad2",
                                        @"iPad2,2"   : @"iPad2",
                                        @"iPad2,3"   : @"iPad2",
                                        @"iPad2,4"   : @"iPad2",
                                        @"iPad2,5"   : @"iPadMini1",
                                        @"iPad2,6"   : @"iPadMini1",
                                        @"iPad2,7"   : @"iPadMini1",
                                        @"iPhone3,1" : @"iPhone4",
                                        @"iPhone3,2" : @"iPhone4",
                                        @"iPhone3,3" : @"iPhone4",
                                        @"iPhone4,1" : @"iPhone4S",
                                        @"iPhone5,1" : @"iPhone5",
                                        @"iPhone5,2" : @"iPhone5",
                                        @"iPhone5,3" : @"iPhone5C",
                                        @"iPhone5,4" : @"iPhone5C",
                                        @"iPad3,1"   : @"iPad3",
                                        @"iPad3,2"   : @"iPad3",
                                        @"iPad3,3"   : @"iPad3",
                                        @"iPad3,4"   : @"iPad4",
                                        @"iPad3,5"   : @"iPad4",
                                        @"iPad3,6"   : @"iPad4",
                                        @"iPhone6,1" : @"iPhone5S",
                                        @"iPhone6,2" : @"iPhone5S",
                                        @"iPad4,1"   : @"iPadAir1",
                                        @"iPad4,2"   : @"iPadAir2",
                                        @"iPad4,4"   : @"iPadMini2",
                                        @"iPad4,5"   : @"iPadMini2",
                                        @"iPad4,6"   : @"iPadMini2",
                                        @"iPad4,7"   : @"iPadMini3",
                                        @"iPad4,8"   : @"iPadMini3",
                                        @"iPad4,9"   : @"iPadMini3",
                                        @"iPhone7,1" : @"iPhone6Plus",
                                        @"iPhone7,2" : @"iPhone6",
                                        @"iPhone8,1" : @"iPhone6S",
                                        @"iPhone8,2" : @"iPhone6SPlus",
                                        @"iPhone8,4" : @"iPhone SE",
                                        @"iPhone9,1" : @"iPhone 7",
                                        @"iPhone9,2" : @"iPhone 7 Plus",
                                        @"iPhone9,3" : @"iPhone 7",
                                        @"iPhone9,4" : @"iPhone 7 Plus",
                                        @"iPhone10,3" : @"iPhoneX",
                                        @"iPhone10,6" : @"iPhoneX",
                                        @"iPhone11,2" : @"iPhoneXS",
                                        @"iPhone11,4" : @"iPhoneS Max",
                                        @"iPhone11,6" : @"iPhoneS Max",
                                        @"iPhone11,8" : @"iPhoneXR"
                                        };
    
    if(![[deviceNamesByCode allKeys]containsObject:code]) return status;
    
    [deviceNamesByCode enumerateKeysAndObjectsUsingBlock:^(NSString*  _Nonnull key, NSString*  _Nonnull obj, BOOL * _Nonnull stop) {
        if ([key isEqualToString:code]) {
            status = obj;
            *stop = YES;
        }
    }];
    
    return status;
}


/**
 * 操作系统的版本号
 * @author Sam
 * @return e.g:@"4.0"
 */
+(NSString*)segDeviceSystemVersion{
    return [UIDevice currentDevice].systemVersion;
}


/// 把图片切到指定的尺寸 从中间开始改变大小
+ (UIImage*)OriginImage:(UIImage*)image scaleToSize:(CGSize)targetSize
{
    UIGraphicsBeginImageContext(targetSize); //size 为CGSize类型，即你所需要的图片尺寸
    
    [image drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];
    
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return scaledImage; //返回的就是已经改变的图片
    //    if (!image) {
    //        return nil;
    //    }
    //
    //    CGFloat imageWidth = image.size.width;
    //    CGFloat imageHeight = image.size.width;
    //
    //    CGFloat ScaleWidth = imageWidth > targetSize.width ? targetSize.width:imageWidth;
    //    CGFloat ScaleHeight = imageHeight > targetSize.height ? targetSize.height:imageHeight;
    //
    //    CGFloat ScaleX = 0;
    //    CGFloat ScaleY = 0;
    //
    //    ScaleX = imageWidth > targetSize.width ? (imageWidth - ScaleWidth) * 0.5 : 0;
    //    ScaleY = imageHeight > targetSize.height ? (imageHeight - ScaleHeight) * 0.5 : 0;
    //
    //    CGImageRef  imageRef = CGImageCreateWithImageInRect([image CGImage], CGRectMake(ScaleX, ScaleY, ScaleWidth, ScaleHeight));
    //
    //    return [UIImage imageWithCGImage:imageRef];
}

+ (void)setObj:(id)obj WithSize:(CGFloat)fontSize textColor:(UIColor*)color
{
    UIColor* color_ = nil;//kColor_1;
    
    if ([obj isKindOfClass:[UILabel class]]) {
        UILabel* label = (UILabel*)obj;
        
        [label setFont:[UIFont systemFontOfSize:fontSize]];
        if (color == nil) {
            
            [label setTextColor:color_];
        }
        else {
            [label setTextColor:color];
        }
    }
    
    if ([obj isKindOfClass:[UIButton class]]) {
        UIButton* btn = (UIButton*)obj;
        
        [btn.titleLabel setFont:[UIFont systemFontOfSize:fontSize]];
        
        if (color == nil) {
            
            [btn setTitleColor:color_ forState:UIControlStateNormal];
        }
        else {
            [btn setTitleColor:color forState:UIControlStateNormal];
        }
    }
    if ([obj isKindOfClass:[UITextField class]]) {
        UITextField* textField = (UITextField*)obj;
        
        [textField setFont:[UIFont systemFontOfSize:fontSize]];
        
        if (color == nil) {
            
            [textField setTextColor:color_];
        }
        else {
            [textField setTextColor:color];
        }
    }
}


/**
 * 任意对象类数据类型转成NSString
 * @author Sam
 * @param objStr 任意类型的数据
 */
+ (NSString*)ValueToString:(id)objStr
{
    if ([objStr isEqual:nil]) {
        return [NSString string];
    }
    
    if ([objStr isEqual:[NSNull null]]) {
        return [NSString string];
    }
    
    if ([objStr isKindOfClass:[NSString class]]) {
        return objStr;
    }
    
    if ([objStr isKindOfClass:[NSNumber class]]) {
        return [NSString stringWithFormat:@"%@", objStr];
    }
    
    return [NSString string];
}

/**
 任意对象类型转换成NSInteger

 @param objStr 任意对象数据
 @return integer
 */
+ (NSInteger)ValueToInteger:(id)objStr
{
    if ([objStr isEqual:[NSNull null]]) {
        return 0;
    }
    
    if ([objStr isKindOfClass:[NSNumber class]]) {
        return [objStr integerValue];
    }
    
    if ([objStr isKindOfClass:[NSString class]]) {
        return [objStr integerValue];
    }
    
    return (NSInteger)objStr;
}

+(NSString*)timeLeftWithSecond:(NSString*)second{
    
    long long  day = second.longLongValue  / (long)86400;
    long long  day_left = second.longLongValue % (long)86400;
    
    long long  hour = day_left  / (long)3600;
    long long  hour_left = day_left % (long)3600;
    long long  min = hour_left  / (long)60;
    
    NSString *_day = day > 0 ? [NSString stringWithFormat:@"%zd天",day] : @"";
    NSString *_hour = hour > 0 ? [NSString stringWithFormat:@"%zd小时",hour] : @"";
    NSString *_min = min > 0 ? [NSString stringWithFormat:@"%zd分钟",min] : @"";
    return  [NSString stringWithFormat:@"%@%@%@",_day,_hour,_min];
}

/**
 * 返回指定格式的当前时间字符串
 * @author Sam
 * @param format  当前时间的格式
 */
+(NSString*)segCurrentTimeWithTimeFormate:(NSString*)format{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = format;
    return [dateFormatter stringFromDate:[NSDate date]];
    
}

///  统计字符串的宽高
///
///  @param string   字符串内容
///  @param width    闲置最大的宽度
///  @param fontSize 字符串字体的大小
+ (CGSize)sizeWithConstrainedWithString:(NSString*)string
                                ToWidth:(CGFloat)width
                         WithFontOfSize:(CGFloat)fontSize
{
    NSDictionary* attribute = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontSize] };
    
    CGSize textSize = [string boundingRectWithSize:CGSizeMake(width, 0) options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    
    return textSize;
}

/**
 获取文本宽度
 
 @param font 字体大小
 @param height 文本高度
 @param text 文本内容
 @return 文本宽度
 */
+ (CGFloat)getWidthWithFontSize:(CGFloat)font
                         height:(CGFloat)height
                           text:(NSString *)text
{
    NSDictionary *attr = @{NSFontAttributeName : [UIFont systemFontOfSize:font]};
    CGFloat width = [text boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                       options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                    attributes:attr
                                       context:nil].size.width;
    return width;
}

/**
 * 获取显示时间
 * @author Wendy
 * @param time 时间戳字符串 13位
 * @return 显示的时间格式
 */
+ (NSString*)getShowDateWithTimer:(NSString*)time
{
    NSDate* timeDate = [[NSDate alloc] initWithTimeIntervalSince1970:[time longLongValue] / 1000.0];
    NSDate *nowDate = [NSDate date];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd";
    NSString* timeStr = [dateFormatter stringFromDate:timeDate];
    NSString* nowStr = [dateFormatter stringFromDate:nowDate];
    
    //差距时间 用于计算分钟和小时
    NSTimeInterval diffrentTime = [nowDate timeIntervalSinceDate:timeDate];
    NSInteger min = (long)floor(diffrentTime / 60.f);
    NSInteger hours = (long)floor(diffrentTime / (60.f * 60.f));
    
    //差距时间 用于计算天数差距(这样算出的天数是根据日期间隔算的，不是根据时间间隔)
    NSDate *timeDay = [dateFormatter dateFromString:timeStr];
    NSDate *nowDay = [dateFormatter dateFromString:nowStr];
    NSTimeInterval diffrentTime2 = [nowDay timeIntervalSinceDate:timeDay];
    NSInteger days = (long)floor(diffrentTime2 / (24.f * 60.f * 60.f));//向下取整
    
    //用于比较是否当年、当月
    NSString *year = [timeStr substringWithRange:NSMakeRange(0, 4)];
    NSString *month = [timeStr substringWithRange:NSMakeRange(5, 2)];
    NSString *yearCurrent = [nowStr substringWithRange:NSMakeRange(0, 4)];
    NSString *monthCurrent = [nowStr substringWithRange:NSMakeRange(5, 2)];
    
    /*  “刚刚”：1分钟以内；
     “xx分钟前”：1-60分钟以内；
     “xx小时前”：>1小时，显示“xxx小时前”
     “昨天”：当前日期的前一天（如跨天，一小时内显示xx分钟前，超过一小时显示昨天：），显示昨天；
     ”前天”：当前日期的前两天，显示“前天”；
     */
    
    if (days <= 1) {//今天、昨天
        if (min < 1) {//1分钟以内；
            return @"刚刚";
        }
        if(min >= 1 && min < 60 ) {//1-60分钟以内；
            return [NSString stringWithFormat:@"%ld分钟前",(long)min];
        }
        if (hours >=1 && days == 0 && [timeStr isEqualToString:nowStr]) {//超过一小时
            return [NSString stringWithFormat:@"%ld小时前",(long)hours];
        }
        return @"昨天";
    }
    if (days == 2) {//前天
        return @"前天";
    }
    //不是本年就返回 YYYY
    if (![year isEqualToString:yearCurrent]) {
        return [NSString stringWithFormat:@"%@年",year];
    }
    /*
     “xx个月前”：如当前月份-发布月份>0，则显示“xx个月前”；
     如跨月，2天以内，仍按照原有规则处理“刚刚、xxx分钟前、xx小时前、昨天、前天”这几种情况；如超过，显示“1个月前”
     */
    if (![month isEqualToString:monthCurrent]) {
        NSInteger months = [monthCurrent integerValue] - [month integerValue];
        return [NSString stringWithFormat:@"%ld个月前",(long)months];
    }else {//”xx天前”：2天<日期<31天；
        return [NSString stringWithFormat:@"%ld天前",(long)days];
    }
}

+ (NSString*)timeForTodayWithType:(SEGSystemUtils_Time_Today_Type)type
{
    
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSString* nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    switch (type) {
            case SEGSystemUtils_Time_Today_Type_Today: { //yyyy-MM-dd HH:mm
                return nowDateStr;
            } break;
            case SEGSystemUtils_Time_Today_Type_Month_Day: { //MM-dd
                return [nowDateStr substringWithRange:NSMakeRange(5, 5)];
            } break;
            
            case SEGSystemUtils_Time_Today_Type_Hour_Min: { //HH:mm
                return [nowDateStr substringWithRange:NSMakeRange(11, 5)];
            } break;
            case SEGSystemUtils_Time_Today_Type_Year: { //yyyy
                return [nowDateStr substringWithRange:NSMakeRange(0, 4)];
            } break;
            case SEGSystemUtils_Time_Today_Type_Month: { //MM
                return [nowDateStr substringWithRange:NSMakeRange(5, 2)];
            } break;
            case SEGSystemUtils_Time_Today_Type_Day: { //dd
                return [nowDateStr substringWithRange:NSMakeRange(8, 2)];
            } break;
            case SEGSystemUtils_Time_Today_Type_Hour: { //HH
                return [nowDateStr substringWithRange:NSMakeRange(11, 2)];
            } break;
            case SEGSystemUtils_Time_Today_Type_Min: { //mm
                return [nowDateStr substringWithRange:NSMakeRange(14, 2)];
            } break;
        default:
            break;
    }
    return nowDateStr;
}

+(NSInteger)timestampWithTime:(NSString *)time WithType:(SEGSystemUtils_Time_Today_Type)type{
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"Asia/Beijing"]];
    [inputFormatter setDateFormat:[self timeDateFormatType:type]];
    NSDate* inputDate = [inputFormatter dateFromString:time];
    NSInteger timeSp = [[NSNumber numberWithDouble:[inputDate timeIntervalSince1970]] integerValue];
    return timeSp;
}

+(NSString*)timeDateFormatType:(SEGSystemUtils_Time_Today_Type)type{
    switch (type) {
            case SEGSystemUtils_Time_Today_Type_Today:
        {return @"yyyy-MM-dd HH:mm";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Year_Month_Day:
        {return @"yyyy-MM-dd";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Month_Day:
        {return @"MM-dd";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Hour_Min:
        {return @"HH:mm";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Year:
        {return @"yyyy";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Month:
        {return @"MM";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Day:
        {return @"dd";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Hour:
        {return @"HH";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Min:
        {return @"mm";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Today_T:
        {return @"yyyy-MM-dd'T'HH:mm:ss";
            break;
        }
            case SEGSystemUtils_Time_Today_Type_Today_ss:
        {return @"yyyy-MM-dd HH:mm:ss";
            break;
        }
            
    }
}

+ (NSString*)time:(NSString *)time Type:(SEGSystemUtils_Time_Today_Type)type
{
    NSDate* timeDate =  [NSDate dateWithTimeIntervalSince1970:[time longLongValue]];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    dateFormatter.dateFormat = [self timeDateFormatType:type];
    dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:+28800];
    NSString* nowDateStr = [dateFormatter stringFromDate:timeDate];
    return nowDateStr;
}

/**
 * 获取app名称
 * @author Sam
 */
+(NSString*)segAppName{
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    return [infoDictionary objectForKey:@"CFBundleDisplayName"];
}

/**
 *  MD5加密
 */
+ (NSString*)md5:(NSString*)str
{
    const char* cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result); // This is the md5 call
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]];
}

//根据指定时间的字符串格式和时间 格式例如yyyy-MM-dd HH:mm:ss:SSS
+ (NSString*)stringDateByFormatString:(NSString*)formatString withDate:(NSDate*)date
{
    static NSDateFormatter* dateFromatter = nil;
    NSString* strDate = nil;
    if (!dateFromatter) {
        dateFromatter = [[NSDateFormatter alloc] init];
        [dateFromatter setTimeStyle:NSDateFormatterShortStyle];
    }
    
    if (date == nil) {
        return @"";
    }
    
    @synchronized(dateFromatter)
    {
        //        [dateFromatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
        if (formatString != nil) {
            [dateFromatter setDateFormat:formatString];
        }
        strDate = [dateFromatter stringFromDate:date];
    }
    
    return strDate;
}

//通过时间戳获取时间
+(NSString *)getTimeWithTimeStr:(NSString *)timeStr timeFormat:(NSString *)format
{
    CGFloat time = [timeStr doubleValue];
    
    if (timeStr.length == 13) {
        time = [timeStr doubleValue]/1000;
    }
    
    NSDate *detaildate=[NSDate dateWithTimeIntervalSince1970:time];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //设置时区
    [dateFormatter setTimeZone:[NSTimeZone localTimeZone]];
    
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:format];
    NSString * str1 = [dateFormatter stringFromDate:detaildate];
    
    return str1;
}

/**
 根据给定的小时的毫秒级时间戳获得今天该小时完整的时间字符串
 @param dateStr 日期字符串 yyyy-MM-dd
 @param miliSecond 毫秒级小时时间戳
 @param formatterStr 返回的时间格式
 @return 时间字符串
 */
+(NSString *)getTimeStrWithDate:(NSString *)dateStr milliSecond:(NSString *)miliSecond formatterStr:(NSString *)formatterStr{
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSTimeZone *timeZone = [[NSTimeZone alloc] initWithName:@"Asia/Shanghai"];
    [greCalendar setTimeZone: timeZone];
    
    //给定日期的日期成分
    NSDateComponents *dateComponents = [greCalendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay  fromDate:[self dateFromString:dateStr withFormatString:@"yyyy-MM-dd"]];
    
    // 定义一个NSDateComponents对象，设置一个时间点
    NSDateComponents *dateComponentsForDate = [[NSDateComponents alloc] init];
    [dateComponentsForDate setDay:dateComponents.day];
    [dateComponentsForDate setMonth:dateComponents.month];
    [dateComponentsForDate setYear:dateComponents.year];
    [dateComponentsForDate setHour:00];
    [dateComponentsForDate setMinute:00];
    
    NSDate *dateFromDateComponentsForDate = [greCalendar dateFromComponents:dateComponentsForDate];
    
    //今天0点时间戳字符串
    long long time = [self getDateTimeTOMilliSeconds:dateFromDateComponentsForDate] ;
    
    //返回给定毫秒时间戳在当天的时间格式
    NSString *timeStr = [NSString stringWithFormat:@"%.0f",time + [miliSecond doubleValue]];
    return [self getTimeWithTimeStr:timeStr timeFormat:formatterStr];
}

+(long long)getDateTimeTOMilliSeconds:(NSDate *)datetime
{
    NSTimeInterval interval = [datetime timeIntervalSince1970];
    long long totalMilliseconds = interval*1000 ;
    return totalMilliseconds;
}

//字符串转换成日期
+ (NSDate*)dateFromString:(NSString*)datestring withFormatString:(NSString*)formatString;
{
    static NSDateFormatter* formatter = nil;
    if (!formatter) {
        formatter = [[NSDateFormatter alloc] init];
        //        [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    }
    
    NSDate* date = nil;
    @synchronized(formatter)
    {
        //#define kDEFAULT_DATE_TIME_FORMAT (@"yyyy-MM-dd'T'HH:mm:ss'Z'")
        [formatter setDateFormat:formatString];
        date = [formatter dateFromString:datestring];
    }
    return date;
}

/**
 消息中心中的详情界面 数据格式转换
 
 @param string 时间字符串 格式为yyyy-MM-dd HH:mm
 @return 显示时间 yyyy年MM月dd日 HH:mm／ MM月dd日 HH:mm／HH:mm
 */
+ (NSString *)getTimeStringInMessageDetailVCWithString:(NSString *)string
{
    NSDate* timeDate = [SEGUtils dateFromString:string withFormatString:@"yyyy-MM-dd HH:mm"];
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy年MM月dd日 HH:mm";
    NSString* timeStr = [dateFormatter stringFromDate:timeDate];
    NSString* nowDateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    NSString *showString;
    
    //不是本年就返回 YYYY
    if ([[timeStr substringWithRange:NSMakeRange(0, 4)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(0, 4)]].location == NSNotFound) {
        showString = timeStr;
    }
    else {
        //是不是今天
        if ([[timeStr substringWithRange:NSMakeRange(5, 5)] rangeOfString:[nowDateStr substringWithRange:NSMakeRange(5, 5)]].location == NSNotFound) {
            showString =  [timeStr substringWithRange:NSMakeRange(5, 12)];//MM月dd日 HH:mm
        }
        else {
            showString =  [timeStr substringWithRange:NSMakeRange(12, 5)];//HH:mm
        }
    }
    
    return showString;
}

///点赞数
+(NSString*)seg_numWithNum:(NSString*)num{
    if (!num)return @"0";
    NSInteger count = num.integerValue;
    if (count < 10000) {
        return [NSString stringWithFormat:@"%zd",count];
    }
    NSInteger wan = count / 10000;
    return [NSString stringWithFormat:@"%zd万+",wan];
}

/// 获取埋点名称 为空时用"-"
+ (NSString *)getAnalyticsNameString:(NSString *)name
{
    NSString *nameString = ValueToString(name);
    if (!name || name.length == 0 ) {
        nameString = @"-";
    }
    return nameString;
}

/// 过滤地址信息中的“来自”
+ (NSString *)getShowAddressWithString:(NSString *)string
{
    NSString *address = [string stringByReplacingOccurrencesOfString:@" " withString:@""];//去掉空格
    if ([address rangeOfString:@"来自"].location != NSNotFound) {
        address = [address substringFromIndex:2];
    }
    return address;
}


//图片方向
+ (UIImage*)fixOrientation:(UIImage*)srcImg
{
    if (srcImg.imageOrientation == UIImageOrientationUp)
    return srcImg;
    CGAffineTransform transform = CGAffineTransformIdentity;
    switch (srcImg.imageOrientation) {
            case UIImageOrientationDown:
            case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, srcImg.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
            case UIImageOrientationUp:
            case UIImageOrientationUpMirrored:
            break;
    }
    
    switch (srcImg.imageOrientation) {
            case UIImageOrientationUpMirrored:
            case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, srcImg.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            case UIImageOrientationUp:
            case UIImageOrientationDown:
            case UIImageOrientationLeft:
            case UIImageOrientationRight:
            break;
    }
    
    CGContextRef ctx = CGBitmapContextCreate(NULL, srcImg.size.width, srcImg.size.height,
                                             CGImageGetBitsPerComponent(srcImg.CGImage), 0,
                                             CGImageGetColorSpace(srcImg.CGImage),
                                             CGImageGetBitmapInfo(srcImg.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (srcImg.imageOrientation) {
            case UIImageOrientationLeft:
            case UIImageOrientationLeftMirrored:
            case UIImageOrientationRight:
            case UIImageOrientationRightMirrored:
            CGContextDrawImage(ctx, CGRectMake(0, 0, srcImg.size.height, srcImg.size.width), srcImg.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0, 0, srcImg.size.width, srcImg.size.height), srcImg.CGImage);
            break;
    }
    
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage* img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**
 压缩图片
 
 @param tempImage 图片
 @return 压缩后的图片
 */
+(UIImage *)ScaleImage:(UIImage *)tempImage
{
    //加载Logo
    //压缩图片
    
    CGFloat hh = 0;
    if (tempImage.size.width>tempImage.size.height)
    {
        
        hh = tempImage.size.width;
    }
    else
    {
        hh = tempImage.size.height;
    }
    
    UIImage *scaleImageView = nil;
    if (hh>1280)
    {
        CGFloat wh = 1280/hh;
        scaleImageView = [self OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width*wh, tempImage.size.height*wh)];
    }
    else
    {
        scaleImageView = [self OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width, tempImage.size.height)];
    }
    return scaleImageView;
}

//等比压缩图片
+ (UIImage*)scaleImage:(UIImage*)aImage maxSize:(CGSize)aSize
{
    if (!aImage) {
        return nil;
    }
    
    CGSize oldSize = aImage.size;
    float newWidth = 0.0;
    float newHeight = 0.0;
    //宽不超过200 高不超过100
    if (oldSize.width <= aSize.width && oldSize.height <= aSize.height) { //当宽高都不超过
        return aImage;
    }
    if (oldSize.width > aSize.width && oldSize.height <= aSize.height) { //当宽超过  高不超过
        newWidth = aSize.width;
        float w = oldSize.width / aSize.width;
        newHeight = oldSize.height / w;
    }
    if (oldSize.width <= aSize.width && oldSize.height > aSize.height) { //当宽不超过  高超过
        newHeight = aSize.height;
        float h = oldSize.height / aSize.height;
        newWidth = oldSize.width / h;
    }
    if (oldSize.width > aSize.width && oldSize.height > aSize.height) { //当宽 高 都超过
        float w = oldSize.width / aSize.width;
        float h = oldSize.height / aSize.height;
        float n = (w > h) ? w : h;
        newWidth = oldSize.width / n;
        newHeight = oldSize.height / n;
    }
    CGSize newSize = CGSizeMake(newWidth, newHeight);
    UIGraphicsBeginImageContext(newSize);
    [aImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}

/// 压缩图片使图片文件小于指定大小
/// @param image image
/// @param maxLength 压缩最大长度(bytes)
+ (NSData *)compressImageQuality:(UIImage*)image maxLength:(NSInteger)maxLength {
   CGFloat compression = 1;
   NSData *data = UIImageJPEGRepresentation(image, compression);
   if (data.length < maxLength) return data;
   CGFloat max = 1;
   CGFloat min = 0;
   for (int i = 0; i < 6; ++i) {
       compression = (max + min) / 2;
       data = UIImageJPEGRepresentation(image, compression);
       if (data.length < maxLength * 0.9) {
           min = compression;
       } else if (data.length > maxLength) {
           max = compression;
       } else {
           break;
       }
   }
   
   if (data.length > maxLength) {
       UIImage *nImage = [self drawImage:image bySize:CGSizeMake(image.size.width*0.5, image.size.height*0.5)];
       data = [self compressImageQuality:nImage maxLength:maxLength];
   }
   
   return data;
}

// 根据 aSize 返回一个新的image
+ (UIImage *)drawImage:(UIImage *)image bySize:(CGSize)aSize; {
    UIGraphicsBeginImageContext(aSize);
    [image drawInRect:CGRectMake(0, 0, aSize.width, aSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return newImage;
}


/**
 *  创建线条
 *
 *  @param rect 视图大小位置
 *
 *
 */
+ (UIView*)CreateLineView:(CGRect)rect
{
    UIView* lineView = [[UIView alloc] initWithFrame:rect];
    lineView.backgroundColor = [UIColor colorWithRed:229 / 255.0f green:229 / 255.0f blue:229 / 255.0f alpha:1.0f];
    return lineView;
}

+ (BOOL)isBlankString:(NSString*)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length] == 0) {
        return YES;
    }
    return NO;
}
/**
 字符串转数组
 
 @param jsonString jsonStr
 @return 数组
 */
+ (NSArray *)arrayWithJsonString:(NSString *)jsonString
{
    if ([jsonString isKindOfClass:[NSArray class]] || [jsonString isKindOfClass:[NSMutableArray class]]) {
        return (NSArray *)jsonString;
    }
    
    if (jsonString == nil || jsonString.length == 0) {
        return @[];
    }
    
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSArray *array = [NSJSONSerialization JSONObjectWithData:jsonData
                                                     options:NSJSONReadingMutableContainers
                                                       error:&err];
    NSLog(@"array = %@", array);
    return array;
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

/**
 获取富文本
 */
+(NSMutableAttributedString *)getAttributeStringWith:(UIColor *)color font:(UIFont *)font textStr:(NSString *)textStr lineSpace:(CGFloat)lineSpace alignment:(NSTextAlignment)alignment
{
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    [paragraphStyle setLineSpacing:lineSpace];
    paragraphStyle.alignment = alignment;
    NSDictionary *dictAttr = @{NSParagraphStyleAttributeName:paragraphStyle,NSFontAttributeName:font,
                               NSForegroundColorAttributeName:color
                               };
    textStr = [SEGUtils ValueToString:textStr];
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString:textStr attributes:dictAttr];
    
    return attributedStr;
}

/**
 *  修改文字的属性 颜色 字体 范围
 */
+ (NSMutableAttributedString *)getAttributedWithString:(NSString *)string Color:(UIColor *)color font:(UIFont *)font range:(NSRange)range
{
    if (string.length >= range.length) {
        NSMutableAttributedString *strAttributed = [[NSMutableAttributedString alloc] initWithString:string];
        [strAttributed addAttribute:NSForegroundColorAttributeName value:color range:range];
        [strAttributed addAttribute:NSFontAttributeName value:font range:range];
        return strAttributed;
    }
    return nil;
}

/**
 校验attrVaule是否有值
 */
+(BOOL)checkAttrValueWith:(id)attrValue
{
    if (attrValue == nil || [attrValue isKindOfClass:[NSNull class]]) {
        return NO;
    }
    if ([attrValue isKindOfClass:[NSArray class]] || [attrValue isKindOfClass:[NSMutableArray class]] ) {
        if ([attrValue count] > 0) {
            return YES;
        }
        else{
            return NO;
        }
    }
    if ([attrValue isKindOfClass:[NSDictionary class]] || [attrValue isKindOfClass:[NSMutableDictionary class]] ) {
        if ([[attrValue allKeys] count] > 0) {
            return YES;
        }
        else{
            return NO;
        }
    }
    if ([attrValue length] > 0) {
        return YES;
    }
    return NO;
}

//根据当前时间压缩图片添加水印
+(NSData *)ScaleImageAndMakeLogo:(UIImage *)tempImage
{
    //加载Logo
    //压缩图片
    
    CGFloat hh = 0;
    if (tempImage.size.width>tempImage.size.height)
    {
        
        hh = tempImage.size.width;
    }
    else
    {
        hh = tempImage.size.height;
    }
    
    UIImage *scaleImageView = nil;
    if (hh>1280)
    {
        CGFloat wh = 1280/hh;
        scaleImageView = [SEGUtils OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width*wh, tempImage.size.height*wh)];
    }
    else
    {
        scaleImageView = [SEGUtils OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width, tempImage.size.height)];
    }
    
    return [SEGUtils makeWatermarkLogo:scaleImageView];
}

//根据照片拍摄时间压缩图片加载水印
+(NSData *)ScaleImageAndMakeLogo:(UIImage *)tempImage creatDate:(NSDate *)date
{
    //加载Logo
    //压缩图片
    
    CGFloat hh = 0;
    if (tempImage.size.width>tempImage.size.height)
    {
        
        hh = tempImage.size.width;
    }
    else
    {
        hh = tempImage.size.height;
    }
    
    UIImage *scaleImageView = nil;
    if (hh>1280)
    {
        CGFloat wh = 1280/hh;
        scaleImageView = [SEGUtils OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width*wh, tempImage.size.height*wh)];
    }
    else
    {
        scaleImageView = [SEGUtils OriginImage:tempImage scaleToSize:CGSizeMake(tempImage.size.width, tempImage.size.height)];
    }
    
    return [SEGUtils makeWatermarkLogo:scaleImageView creatDate:date];
}

/**
 *  生成水印调用方法
 *
 *  @return 返回图像
 */
+(NSData *)makeWatermarkLogo:(UIImage *)image
{
    /**<添加水印*/
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [dateFormatter stringFromDate:[NSDate date]];
    
    return [SEGUtils addImageLogo:image logo:[UIImage imageWithData:[SEGUtils addImageText:[UIImage imageWithData:[SEGUtils addImageLogo2]] text:dateStr]]];
}

/**
 *  根据照片拍摄时间生成水印调用方法
 *
 *  @return 返回图像
 */
+(NSData *)makeWatermarkLogo:(UIImage *)image creatDate:(NSDate *)date
{
    /**<添加水印*/
    NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *dateStr = [dateFormatter stringFromDate:date];
    
    return [SEGUtils addImageLogo:image logo:[UIImage imageWithData:[SEGUtils addImageText:[UIImage imageWithData:[SEGUtils addImageLogo2]] text:dateStr]]];
}

/**
 *  生成水印图标
 *
 *  @return 返回水印图标
 */
+(NSData *)addImageLogo2
{
    int w = 48+350+20;     //图标+时间背景+偏移量
    int h = 72;
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    //获取上下文
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    
    //添加Logo图片
    UIImage *image = [UIImage imageWithContentsOfFile:SEGPicName(@"AppIcon72_corner")];
    CGContextDrawImage(context, CGRectMake(0, 0, 72, 72), image.CGImage);
    
    //画黑色底框
    CGContextAddRect(context, CGRectMake(92, 0, 350, 72));
    CGContextSetFillColorWithColor(context, [UIColor blackColor].CGColor);
    CGContextFillPath(context);
    
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    NSData *imageData = UIImagePNGRepresentation([UIImage imageWithCGImage:imageMasked]);
    //释放
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageMasked);
    
    return imageData;
}

/**
 *  添加文字水印
 *
 *  @param img   源图像
 *  @param text1 文本
 *
 *  @return 返回图片Data
 */
+(NSData *)addImageText:(UIImage *)img text:(NSString *)text1
{
    
    CGSize size = CGSizeMake(img.size.width, img.size.height); //设置上下文（画布）大小
    UIGraphicsBeginImageContext(size); //创建一个基于位图的上下文(context)，并将其设置为当前上下文
    CGContextRef contextRef = UIGraphicsGetCurrentContext(); //获取当前上下文
    CGContextTranslateCTM(contextRef, 0, img.size.height); //画布的高度
    CGContextScaleCTM(contextRef, 1.0, -1.0); //画布翻转
    CGContextDrawImage(contextRef, CGRectMake(0, 0, img.size.width, img.size.height), [img CGImage]); //在上下文种画当前图片
    
    [[UIColor yellowColor] set]; //上下文种的文字属性
    UIFont *font = [UIFont boldSystemFontOfSize:30];
    
    CGContextTranslateCTM(contextRef, 0, img.size.height); //画布的高度
    CGContextScaleCTM(contextRef, 1.0, -1.0); //画布翻转
    
    [text1 drawInRect:CGRectMake(102,15,350, 72) withFont:font];
    UIImage *targetimg =UIGraphicsGetImageFromCurrentImageContext(); //从当前上下文种获取图片
    
    UIGraphicsEndImageContext(); //移除栈顶的基于当前位图的图形上下文。
    //    return UIImageJPEGRepresentation(targetimg, 1);
    return UIImagePNGRepresentation(targetimg);
}

/**
 *  添加图片水印
 *
 *  @param img  原图图片
 *  @param logo 水印图片
 *
 *  @return 返回图片
 */
+(NSData *)addImageLogo:(UIImage *)img logo:(UIImage *)logo
{
    //get image width and height
    int w = img.size.width;
    int h = img.size.height;
    
    //将屏幕分成三分
    int wOffset = w/3;
    
    //等比压缩水印
    CGFloat logoH = logo.size.height/(logo.size.width/wOffset);
    
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
    
    //获取上下文
    CGContextRef context = CGBitmapContextCreate(NULL, w, h, 8, 4 * w, colorSpace, kCGImageAlphaPremultipliedFirst);
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    
    //Create image ref from the context
    
    //添加图片
    CGContextDrawImage(context, CGRectMake(0, 0, w, h), img.CGImage);
    CGContextDrawImage(context, CGRectMake(w-wOffset-20, 26, wOffset, logoH), [logo CGImage]);
    
    CGImageRef imageMasked = CGBitmapContextCreateImage(context);
    
    NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageMasked], 1);
    
    //释放
    CGContextRelease(context);
    CGColorSpaceRelease(colorSpace);
    CGImageRelease(imageMasked);
    return imageData;
}

//获取document路径
+ (NSString*)documentPath
{
    //获取存档对象的路径
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentPath = [paths objectAtIndex:0];
    return documentPath;
}

//获取媒体文件存放路径
+ (NSString*)mideaFilePath
{
    return [[SEGUtils documentPath] stringByAppendingPathComponent:@"midea"];
}

//根据文件名获取媒体文件完整路径
+ (NSString*)mideaFilePathForFileName:(NSString*)aFileName
{
    if (!aFileName) {
        return nil;
    }
    return [[SEGUtils mideaFilePath] stringByAppendingPathComponent:aFileName];
}

//字符串转日期格式
+ (NSDate *)stringToDate:(NSString *)dateString withDateFormat:(NSString *)format
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:format];
    
    NSDate *date = [dateFormatter dateFromString:dateString];
    return [self worldTimeToChina:date];
}
//将世界时间转化为中国区时间
+ (NSDate *)worldTimeToChina:(NSDate *)date
{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    NSInteger interval = [timeZone secondsFromGMTForDate:date];
    NSDate *localeDate = [date  dateByAddingTimeInterval:interval];
    return localeDate;
}

// 判断app是否第一次启动或者更新后第一次启动
+(BOOL)isFirstLoad{
    //获取版本号
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    
    //本地存储的版本号
    NSString *lastRunVersion = [defaults objectForKey:LAST_RUN_VERSION_KEY];
    
    if (!lastRunVersion) {// 用户第一次启动
        [defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];
        return YES;
    }else if (![lastRunVersion isEqualToString:currentVersion]){// app更新
        [defaults setObject:currentVersion forKey:LAST_RUN_VERSION_KEY];
        return YES;
    }
    return NO;
}

/**
 *  判断输入的内容是不是为空
 */
+ (BOOL)isEmpty:(NSString*)str
{
    
    if (!str) {
        return true;
    }
    else {
        //A character set containing only the whitespace characters space (U+0020) and tab (U+0009) and the newline and nextline characters (U+000A–U+000D, U+0085).
        NSCharacterSet* set = [NSCharacterSet whitespaceAndNewlineCharacterSet];
        
        //Returns a new string made by removing from both ends of the receiver characters contained in a given character set.
        NSString* trimedString = [str stringByTrimmingCharactersInSet:set];
        
        if ([trimedString length] == 0) {
            return true;
        }
        else {
            return false;
        }
    }
}

+(BOOL)isNeedMultiLineWithStr:(NSString *)str
                   withHeight:(CGFloat)height
                    withWidth:(CGFloat)width
                     withFont:(CGFloat)font {
    CGFloat myWidth = [str boundingRectWithSize:CGSizeMake(MAXFLOAT, height)
                                        options:NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin
                                     attributes:@{NSFontAttributeName : [UIFont systemFontOfSize:font]}
                                        context:nil].size.width;
    if (myWidth <= width) {
        return NO;
    } else {
        return YES;
    }
}

/**
 通过URL获取图片大小
 
 @param imageUrl  图片url
 @return size
 */
+ (CGSize)getImageSizeWithImageUrl:(NSString *)imageUrl {
    if (imageUrl.length == 0 || !imageUrl) return CGSizeZero;
    CGSize ImageSize = CGSizeZero;
    NSArray *arr = [imageUrl componentsSeparatedByString:@"_"];
    if (arr.count > 2) {
        ImageSize.width = [arr[1] floatValue];
        ImageSize.height = [[arr[2] componentsSeparatedByString:@"."].firstObject floatValue];
    }
    return ImageSize;
}

+ (void)judgeCameraAuthorizationStatus
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请在iphone的设置-隐私-相机选项中,允许%@访问你的相机",kAppName] message:
                                  nil
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

/**
 *  正则表达式
 *
 *  @param textString 输入字符串
 *  @param code       正则表达式
 *
 *  @return YES匹配  NO不匹配
 */
+ (BOOL)isExpressCode:(NSString *)textString expressStr:(NSString *)code
{
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",code];
    return [numberPre evaluateWithObject:textString];
}


/**
 判断相机权限
 */
- (void)judgeCameraAuthorizationStatus
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) {
        
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        if (authStatus != AVAuthorizationStatusAuthorized) {
            UIAlertView* alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"请在iphone的设置-隐私-相机选项中,允许%@访问你的相机",kAppName] message:
                                  nil
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"确定", @"")
                                                  otherButtonTitles:nil];
            [alert show];
        }
    }
}

/**
 * Hmacsha1算法
 * @author Sam
 * @param text  加密参数
 * @param secret  签名秘钥
 */
+ (NSString *)seg_Hmacsha1:(NSString *)text key:(NSString *)secret {
    NSData *secretData = [secret dataUsingEncoding:NSUTF8StringEncoding];
    NSData *clearTextData = [text dataUsingEncoding:NSUTF8StringEncoding];
    unsigned char result[20];
    CCHmac(kCCHmacAlgSHA1, [secretData bytes], [secretData length], [clearTextData bytes], [clearTextData length], result);
    char base64Result[32];
    size_t theResultLength = 32;
    Base64EncodeData(result, 20, base64Result, &theResultLength,YES);
    NSData *theData = [NSData dataWithBytes:base64Result length:theResultLength];
    NSString *base64EncodedResult = [[NSString alloc] initWithData:theData encoding:NSASCIIStringEncoding];
    return base64EncodedResult;
}
@end

